package com.heba.greenmulu.scan;

import android.content.res.Resources;
import android.os.Bundle;

import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.google.android.material.tabs.TabLayout;
import com.google.gson.Gson;
import com.heba.Cfg;
import com.heba.adapter.FmPagerAdapter;
import com.heba.bean.ItemShareObject;
import com.heba.bean.ShareObject;
import com.heba.bean.product.ItemProductCompareObject;
import com.heba.config.CommonConfig;
import com.heba.fragment.product.ProductInfoFragment;
import com.heba.fragment.scan.ProductCommentFragment;
import com.heba.fragment.scan.ProductNutritionFragment;
import com.heba.fragment.scan.ProductSpecificationFragment;
import com.heba.greenmulu.BaseActivity;
import com.heba.greenmulu.R;
import com.heba.greenmulu.message.ItemMessageSendActivity;
import com.heba.helper.HttpClientHelper;
import com.heba.helper.JSONHttpHelper;
import com.heba.helper.MemberShipHelper;
import com.heba.popupwindow.SharePopupWindow;
import com.heba.popupwindow.callback.ShareListener;
import com.heba.utils.ToastShow;
import com.loopj.android.http.RequestParams;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * 扫描产品进来的页面
 * 产品详情页(显示营养 规格 评价的页面)
 * Created by jason on 2020/1/15.
 */
public class ItemProductDetailActivity extends BaseActivity {

    private View view_background;

    /**
     * tablayout
     */
    private TabLayout tabLayout;
    private ViewPager viewPager;
    private FmPagerAdapter pagerAdapter;

    /**
     * fragment
     */
    private ProductNutritionFragment productNutritionFragment;
    private ProductSpecificationFragment productSpecificationFragment;
    private ProductCommentFragment productCommentFragment;
    private ArrayList<Fragment> fragments = new ArrayList<>();
    private ProductInfoFragment productInfoFragment;


    /**
     * 分享彈出框
     */
    private SharePopupWindow sharePopupWindow;
    private ShareObject shareObject;

    private ItemProductCompareObject productCompareObject;

    /**
     * 接收掃描產品傳遞的數據
     */
    private String productID = "";   //產品ID
    private String barCode = "";    //條形碼
    private int selectIndex = 0;

    private ConstraintLayout bottomLine1;
    private ConstraintLayout bottomLine2;
    private ConstraintLayout bottomLine3;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_scan_product_detail);
        initTopbar();
        findViewById();
        initView();


        getProductContentData();
    }

    @Override
    protected void findViewById() {
        view_background = findViewById(R.id.view_background);
        tabLayout = findViewById(R.id.tabLayout);
        viewPager = findViewById(R.id.viewPager);
        bottomLine1 = findViewById(R.id.bottom_line_1);
        bottomLine2 = findViewById(R.id.bottom_line_2);
        bottomLine3 = findViewById(R.id.bottom_line_3);

    }

    @Override
    protected void initView() {
        img_right.setImageResource(R.drawable.icon_more_white_point);
        shareObject = new ShareObject();

        /**
         * 接收数据
         */
        Bundle bundle = getIntent().getExtras();
        if (null != bundle) {
            productID = bundle.getString(CommonConfig.PRODUCT_ID, "");
            barCode = bundle.getString(CommonConfig.BARCODE, "");
        }

        /**
         * 分享点击事件
         */
        img_right.setOnClickListener(v -> {
            if (null == productCompareObject)
                return;
            view_background.setVisibility(View.VISIBLE);
            shareObject.setShareTitle(productCompareObject.getBrandName());
            shareObject.setShareContent(productCompareObject.getProductName());
            shareObject.setShareImageUrl(productCompareObject.getIcon());
            shareObject.setShareLink(productCompareObject.getLink());
            sharePopupWindow.setShareObject(shareObject);
            sharePopupWindow.showAtLocation(img_right, Gravity.BOTTOM, 0, 0);
        });
    }

    /**
     * 分享彈出框
     */
    private void initPopupWindow() {
        List<ItemShareObject> shareList1 = new ArrayList<>();
        List<ItemShareObject> shareList2 = new ArrayList<>();

        /**
         * 分享至社交軟件
         */
        int[] ids = {R.drawable.icon_more_share_facebook, R.drawable.icon_more_share_whatsapp, R.drawable.icon_more_share_wechat, R.drawable.icon_more_share_friends};
        int[] shareTypes = {CommonConfig.SHARE_TO_FACEBOOK, CommonConfig.SHARE_TO_WHATSAPP, CommonConfig.SHARE_TO_WECHAT, CommonConfig.SHARE_TO_CIRCLE};
        String[] contents = this.getResources().getStringArray(R.array.share_contents_normal);
        for (int i = 0; i < ids.length; i++) {
            ItemShareObject shareObject = new ItemShareObject();
            shareObject.setImageID(ids[i]);
            shareObject.setShareContent(contents[i]);
            shareObject.setShareType(shareTypes[i]);
            shareList1.add(shareObject);
        }

        /**
         * 本地分享
         */
        int[] ids1 = {R.drawable.icon_more_send, R.drawable.icon_more_collection, R.drawable.icon_more_correct, R.drawable.icon_more_tutorial};
        int[] shareTypes1 = {CommonConfig.SHARE_TO_SEND_PRODUCT, CommonConfig.SHARE_TO_COLLECT_PRODUCT, CommonConfig.SHARE_TO_UPDATE_PRODUCT, CommonConfig.SHARE_TO_TUTORIAL};
        String[] contents1 = this.getResources().getStringArray(R.array.share_contents_product);
        for (int i = 0; i < ids1.length; i++) {
            ItemShareObject shareObject = new ItemShareObject();
            shareObject.setImageID(ids1[i]);
            shareObject.setShareContent(contents1[i]);
            shareObject.setShareType(shareTypes1[i]);
            shareList2.add(shareObject);
        }

        sharePopupWindow = new SharePopupWindow(this, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        sharePopupWindow.setShareList(shareList1, shareList2);

        /**
         * 分享接口實現
         */
        sharePopupWindow.setOnShareListener(new ShareListener(ItemProductDetailActivity.this) {

            @Override
            public void sendProduct() {
                Bundle bundle = new Bundle();
                bundle.putInt(CommonConfig.TYPE, CommonConfig.TYPE_SEND_PRODUCT);
                bundle.putString(CommonConfig.MESSAGE_ID, productID);
                openActivity(ItemMessageSendActivity.class, bundle);
            }

            @Override
            public void collectProduct() {
                if (productCompareObject.getIsCollect() == 1) {
                    ToastShow.displayToast(ItemProductDetailActivity.this, getResources().getString(R.string.scan_product_has_been_collect));
                    return;
                }

                /**
                 * 收藏產品
                 */
                new MemberShipHelper(new MemberShipHelper.MembershipListener() {
                    @Override
                    public void Success() {
                        productCompareObject.setIsCollect(1);
                        ToastShow.displayToast(ItemProductDetailActivity.this, getResources().getString(R.string.scan_product_collect_success));
                    }

                    @Override
                    public void Fail(String error) {
                    }
                }).collectProduct(ItemProductDetailActivity.this, productID);
            }

            @Override
            public void updateProduct() {
                Bundle bundle1 = new Bundle();
                bundle1.putString(CommonConfig.PRODUCT_ID, productID);
                openActivity(ItemReportProductActivity.class, bundle1);
            }

            @Override
            public void goTutorial() {
                openActivity(ItemProductInfomationActivity.class);
            }
        });

        sharePopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                view_background.setVisibility(View.GONE);
            }
        });
    }

    /**
     * initFragments
     */
    private void initFragments() {

        productNutritionFragment = ProductNutritionFragment.newInstance(productID, barCode);
//        productSpecificationFragment = ProductSpecificationFragment.newInstance(productID, barCode);
        productInfoFragment = ProductInfoFragment.newInstance(productID, barCode);
        productCommentFragment = ProductCommentFragment.newInstance(productID, barCode);
        fragments.add(productInfoFragment);
        fragments.add(productNutritionFragment);
        fragments.add(productCommentFragment);
    }

    /**
     * 设置自定义tab
     */
    private void setCustomTabView() {
        String[] tabTitles = this.getResources().getStringArray(R.array.scan_product_detail);

        /**
         * 添加tab
         */
        for (int i = 0; i < tabTitles.length; i++) {
            tabLayout.addTab(tabLayout.newTab());
        }

        /**
         * 关联viewpager,设置adapter
         */
        tabLayout.setupWithViewPager(viewPager, false);
        pagerAdapter = new FmPagerAdapter(fragments, getSupportFragmentManager());
        viewPager.setAdapter(pagerAdapter);
        viewPager.setOffscreenPageLimit(2);

        /**
         * 设置tab文字,必须在关联viewpager之后设置，否则文字不显示
         */
        for (int i = 0; i < tabTitles.length; i++) {
            tabLayout.getTabAt(i).setText(tabTitles[i]);
        }

        /**
         * 默認第一項的字體大小和粗細
         */
        TextView title = (TextView) (((LinearLayout) ((LinearLayout) tabLayout.getChildAt(0)).getChildAt(0)).getChildAt(1));
        title.setTextAppearance(R.style.TabLayoutSelectedTextStyle);

        /**
         * tabLayout滑動監聽
         */
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                /**
                 * 設置選中的字體大小和粗細
                 */
                TextView title = (TextView) (((LinearLayout) ((LinearLayout) tabLayout.getChildAt(0)).getChildAt(tab.getPosition())).getChildAt(1));
                title.setTextAppearance(R.style.TabLayoutSelectedTextStyle);

                int position = tabLayout.getSelectedTabPosition();
                Resources resources = getResources();
                DisplayMetrics dm = resources.getDisplayMetrics();
                int width3 = dm.widthPixels -120;

                TranslateAnimation translateAnimation1 = null;
                if (position == 0){
                    translateAnimation1 = new TranslateAnimation((selectIndex)*(width3/3),(position)*(width3/3),0,0);
                    translateAnimation1.setDuration(300);
                    translateAnimation1.setFillEnabled(true);//使其可以填充效果从而不回到原地
                    translateAnimation1.setFillAfter(true);//不回到起始位置
                    bottomLine1.startAnimation(translateAnimation1);
                }else if (position == 1){
                    translateAnimation1 = new TranslateAnimation((selectIndex)*(width3/3),bottomLine2.getX(),0,0);
                    translateAnimation1.setDuration(300);
                    translateAnimation1.setFillEnabled(true);//使其可以填充效果从而不回到原地
                    translateAnimation1.setFillAfter(true);//不回到起始位置
                    bottomLine1.startAnimation(translateAnimation1);
                }else{
                    translateAnimation1 = new TranslateAnimation((selectIndex)*(width3/3),bottomLine3.getX(),0,0);
                    translateAnimation1.setDuration(300);
                    translateAnimation1.setFillEnabled(true);//使其可以填充效果从而不回到原地
                    translateAnimation1.setFillAfter(true);//不回到起始位置
                    bottomLine1.startAnimation(translateAnimation1);
                }


                translateAnimation1.setAnimationListener(new Animation.AnimationListener() {
                    @Override
                    public void onAnimationStart(Animation animation) {

                    }

                    @Override
                    public void onAnimationEnd(Animation animation) {
                        selectIndex = tabLayout.getSelectedTabPosition();
//


                    }

                    @Override
                    public void onAnimationRepeat(Animation animation) {

                    }
                });
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                /**
                 * 設置默認字體大小和粗細
                 */
                TextView title = (TextView) (((LinearLayout) ((LinearLayout) tabLayout.getChildAt(0)).getChildAt(tab.getPosition())).getChildAt(1));
                title.setTextAppearance(R.style.TabLayoutNormalTextStyle);
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }

    /**
     * 獲取產品信息
     */
    private void getProductContentData() {
        progressDialog.show();
        HttpClientHelper client = new HttpClientHelper();
        client.setUseLogin(true);
        RequestParams params = new RequestParams();
        params.put("Leng", Cfg.Leng);
        params.put("Barcode", barCode);
        params.put("ProductID", productID);
        client.get(Cfg.BaseUrl + "/Product/Comparison", params,
                new JSONHttpHelper.JSONHttpResponseHandler(this) {

                    @Override
                    public void Success() {
                        // TODO Auto-generated method stub
                        super.Success();
                        progressDialog.dismiss();
                        try {
                            JSONArray array = new JSONObject(response.trim()).getJSONArray("Result");
                            if (array.length() > 0) {
                                JSONObject object = array.getJSONObject(0);
                                productCompareObject = new Gson().fromJson(object.toString(), ItemProductCompareObject.class);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                        if (null != productCompareObject) {
                            productID = productCompareObject.getProductID();
                        }
                        initFragments();
                        setCustomTabView();
                        initPopupWindow();
                    }

                    public void Failure() {
                        super.Failure();
                        progressDialog.dismiss();
                    }

                });
    }
}
